package Tree;

import java.util.ArrayList;
import java.util.List;

public class 二叉搜索树中的众数 {
    private int count = 0;
    private int maxCount = 0;
    private List<Integer> results = new ArrayList<>();
    private TreeNode pre;

    public int[] findMode(TreeNode root) {
        inorderTraversal(root);
        int[] result = new int[results.size()];
        for (int i = 0; i < results.size(); i++) result[i] = results.get(i);
        return result;
    }

    private void inorderTraversal(TreeNode root) {
        if (root == null) return;
        inorderTraversal(root.left);
        if (pre != null && root.val == pre.val) count++;
        else count = 1;
        if (count == maxCount) results.add(root.val);
        else if (count > maxCount) {
            maxCount = count;
            results.clear();
            results.add(root.val);
        }
        pre = root;
        inorderTraversal(root.right);
    }
}
